-- SPDX-FileCopyrightText: Adam Evyčędo
--
-- SPDX-License-Identifier: AGPL-3.0-or-later

---@diagnostic disable-next-line: lowercase-global, unused-local
function getAlerts(stopID, stopCode, tripID, lineID)
  local whereClause = ""
  if lineID ~= '' then
    whereClause = "where=lines%20like%20'" .. lineID .. "'"
  elseif stopID ~= '' then
    whereClause = "where=points%20like%20'" .. stopID .. "'"
  end

	local http = require("http")
	local json = require("json")

	local error_struct = {
		httpResponseCode=0,
		message="",
		willNextRequestFail=false
	}

	local response, error_message = http.get("https://stibmivb.opendatasoft.com/api/explore/v2.1/catalog/datasets/travellers-information-rt-production/records?" .. whereClause, {
    timeout="30s",
  })

	if response == nil then
		error_struct.message = "while getting alerts: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	if response.status_code ~= 200 then
		error_struct.message = "api returned code " .. response.status_code .. "; " .. response.body
		error_struct.httpResponseCode = response.status_code
		error_struct.willNextRequestFail = true
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	---@diagnostic disable-next-line: redefined-local
	local struct, error_message = json.decode(response.body)

	if struct == nil then
		error_struct.message = "while decoding alerts: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	local alerts = {}
  local i = 1
	for _, entry in ipairs(struct.results) do
    ---@diagnostic disable-next-line: redefined-local
		local content, error_message = json.decode(entry.content)
    if content == nil then
      error_struct.message = "while decoding alert text: " .. error_message
    end
    ---@diagnostic disable-next-line: param-type-mismatch
    for _, alertContent in ipairs(content) do
        alerts[i] = {
          timeRanges={
          	{
          		startDate='0001-01-01T00:00:00.000Z',
          		endDate='9999-12-31T23:59:59.999Z'
          	}
          },
          headers={},
          descriptions={},
          urls={},
          cause=0,
          effect=0
        }
      for lang, text in pairs(alertContent.text[1]) do
        alerts[i].headers[lang] = text
        alerts[i].descriptions[lang] = text
      end
      i = i+1
    end
  end

	---@diagnostic disable-next-line: redefined-local
	local result, error_message = json.encode(alerts)

	if result == nil then
		error_struct.message = "while encoding result: " .. error_message
		local error_json, _ = json.encode(error_struct)
		return "", error_json
	end

	return result, ""
end
